package org.example.bombermanclient.network;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import org.example.bombermanclient.listener.MessageListener;
import org.example.bombermanclient.model.Message;

public class NettyClient {

    private EventLoopGroup group;
    private Channel channel;
    private MessageListener listener;

    public void setListener(MessageListener listener) {
        this.listener = listener;
    }

    public void connect(String host, int port) throws InterruptedException {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline pipeline = ch.pipeline();

                        // 先加拆包器（按行分隔，必须在最前面）
                        pipeline.addLast(new LineBasedFrameDecoder(1024));

                        // JSON 编解码
                        pipeline.addLast(new JsonMessageDecoder());
                        pipeline.addLast(new JsonMessageEncoder());

                        // 业务处理
                        pipeline.addLast(new ClientHandler(listener));
                    }
                });

        ChannelFuture future = bootstrap.connect(host, port).sync();
        channel = future.channel();
    }

    public void sendMessage(Message msg) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(msg);
        }
    }

    public void disconnect() {
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
